package com.xiaochun.hxhj;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.bean.VideoListBean;
import com.myview.CustomProgressDialog;
import com.myview.MyVideoView;
import com.util.DensityUtil;
import com.util.ExitAppUtil;
import com.util.InfoEventMessage;
import com.util.MyLog;
import com.util.RequestManager;
import com.util.ShareUtil;
import com.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;

import butterknife.BindView;

public class VideoDetailActivity extends BaseActivity {
    @BindView(R.id.tv_desc)
    TextView tv_desc;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.videoview)
    MyVideoView videoview;
    @BindView(R.id.tv_share)
    TextView tv_share;
    @BindView(R.id.tv_collect)
    TextView tv_collect;
    @BindView(R.id.seek_progress)
    SeekBar seek_progress;
    @BindView(R.id.tv_time_progress)
    TextView tv_time_progress;
    @BindView(R.id.tv_time_all)
    TextView tv_time_all;
    @BindView(R.id.img_stop)
    ImageView img_stop;
    @BindView(R.id.img_screen)
    ImageView img_screen;

    private List<VideoListBean.DataBeanX.DataBean> booklist = new ArrayList<>();
    private List<VideoListBean.DataBeanX.DataBean> booklisttemp = new ArrayList<>();
    private CustomProgressDialog customProgressDialog;
    private String url;
    private String id;
    private String name;
    private String desc;
    private String collectstatus;
    private String sharelogo;
    private Bitmap bitmap;
    private Bitmap sharebitmap;
    boolean isplayover = false;
    private int currentPosition = 0;
    private long lasttime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        customProgressDialog = new CustomProgressDialog(context, "", R.style.CommProgressDialog);
        WindowManager.LayoutParams params = customProgressDialog.getWindow().getAttributes();
        params.alpha = 0.7f;//取值为0-1之间  0是全透明，1是不透明
        params.dimAmount = 0f;   //取值为0-1之间  1是全黑
        customProgressDialog.getWindow().setAttributes(params);
//        customProgressDialog.show();
    }

    @Override
    protected void initListener() {
        tv_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //分享好友
                String url = "https://f-m.bigchun.com//logo.png";
                netPicToBmp(url);
            }
        });
        tv_collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                collect();
            }
        });

        img_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (DensityUtil.isFastDoubleClick()){
                    return;
                }
                if (isplayover){
                    //说明整段视频播放完毕，重新点击播放按钮，就从头重新播放该段视频
                    //视频的总时长，并关联SeekBar的总长度
                    int duration = videoview.getDuration();
                    Log.e("视频总时长按钮", duration + "  转换成秒  " + duration / 1000);
                    SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");//这里想要只保留分秒可以写成"mm:ss"
                    formatter.setTimeZone(TimeZone.getTimeZone("00:00"));
                    String hms = formatter.format(duration);
                    tv_time_all.setText(hms);

                    //设置SeekBar进度的总长
                    seek_progress.setMax(duration);
                    seek_progress.setProgress(0);
                    videoview.seekTo(0);
                    handler.sendEmptyMessage(0);
                    isplayover = false;
                }
                startAndPause();
            }
        });
        img_screen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (videoview.isPlaying()) {
                    //视频在播放-设置暂停
                    videoview.pause();
                    //按钮状态设置播放
                    img_stop.setImageResource(R.mipmap.icon_playstop);
                }
                int progress = seek_progress.getProgress();
                String time = tv_time_progress.getText().toString().trim();
                Intent intent = new Intent(context,VideoPlayDetailActivity.class);
                intent.putExtra("progress",progress+"");
                intent.putExtra("inittime",time+"");
                intent.putExtra("url",url+"");
                startActivity(intent);
                handler.removeCallbacksAndMessages(null);
            }
        });

    }
    //播放和暂停视频
    private void startAndPause() {
        if (videoview.isPlaying()) {
            //视频在播放-设置暂停
            videoview.pause();
            //按钮状态设置播放
            img_stop.setImageResource(R.mipmap.icon_playstop);
        } else {
            //视频播放
            videoview.start();
            //按钮状态设置暂停
            img_stop.setImageResource(R.mipmap.icon_play);
        }
    }
    @Override
    protected int initLayout() {
        return R.layout.activity_videodetail;
    }

    @Override
    protected void initView() {

        changeTitle("详情");
//        EventBus.getDefault().register(this);
        url = getIntent().getStringExtra("url");
        id = getIntent().getStringExtra("id");
        name = getIntent().getStringExtra("name");
        desc = getIntent().getStringExtra("desc");
        collectstatus = getIntent().getStringExtra("collectstatus");
//        1 为已收藏   0 未收藏
        if ("0".equals(collectstatus)){
            tv_collect.setText("收藏");
        }else if ("1".equals(collectstatus)){
            tv_collect.setText("取消收藏");
        }
        tv_name.setText(name);
        tv_desc.setText(desc);
        videoview.setVideoURI(Uri.parse(url));
//        videoview.start();
        getData();

        seek_progress.setOnSeekBarChangeListener(mSeekBarListener);
        videoview.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {

                Log.e("播放完成", "时间暂停");
                handler.removeMessages(0);
                String trim = tv_time_all.getText().toString().trim();
                tv_time_progress.setText(trim);
                videoview.pause();
                //按钮状态设置播放
                img_stop.setImageResource(R.mipmap.icon_playstop);
                isplayover = true;


            }
        });
        //设置发生错误监听，如果不设置videoview会向用户提示发生错误
        videoview.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                return false;
            }
        });
        //设置在视频文件在加载完毕以后的回调函数   168160   167844
        videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                    @Override
                    public boolean onInfo(MediaPlayer mp, int what, int extra) {
                        if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START)
                            videoview.setBackgroundColor(Color.TRANSPARENT);
                        return true;
                    }
                });
                //视频的总时长，并关联SeekBar的总长度
                int duration = videoview.getDuration();
                Log.e("视频总时长准备", duration + "  转换成秒  " + duration / 1000);
                SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");//这里想要只保留分秒可以写成"mm:ss"
                formatter.setTimeZone(TimeZone.getTimeZone("00:00"));
                String hms = formatter.format(duration);
                tv_time_all.setText(hms);

                //设置SeekBar进度的总长
                seek_progress.setMax(duration);
                seek_progress.setProgress(currentPosition);
                videoview.seekTo(currentPosition);
                videoview.start();

                handler.sendEmptyMessage(0);

            }
        });
        //设置videoView的点击监听
        videoview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        long l = System.currentTimeMillis();
                        if (lasttime == 0){
                            lasttime = l;
                        }else{
                            long timecha = l - lasttime;
                            if (timecha > 500){
                                lasttime = l;
                            }else{
                                lasttime = l;
                                startAndPause();
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP:


                        break;
                }

                return false;
            }
        });


        videoview.setPlayListener(new MyVideoView.PlayListener() {
            @Override
            public void onPause() {
                Log.e("视频播放暂停位置", currentPosition + "    暂停毫秒");

                seek_progress.setProgress(currentPosition);
            }

            @Override
            public void onStart() {
                int as = currentPosition + 1;
                Log.e("视频播放开始位置", as + "    开始毫秒");
//                videoView.seekTo(as);
                videoview.seekTo(currentPosition);
            }
        });



    }
    /**
     * 进度拖动条监听器
     */
    private SeekBar.OnSeekBarChangeListener mSeekBarListener = new SeekBar.OnSeekBarChangeListener() {
        // 通知进度已经被修改
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                videoview.seekTo(progress);
                Message msg = Message.obtain();
                msg.what = 0;
                msg.obj = seekBar.getProgress();
                handler.removeMessages(0);
//                handler.sendMessageAtTime(msg, 0);// 1秒之后开始发送更新进度的消息
                handler.sendEmptyMessage(0);
            }
        }

        // 通知用户已经开始一个触摸拖动手势
        public void onStartTrackingTouch(SeekBar seekBar) {
        }
        // 通知用户触摸手势已经结束
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    };



    @Override
    protected void initData() {

    }
    private void getData() {
        String token = getUserInfo("token");
        String url = myapp.getWebConfig() + "/api/banner/vedioDetail";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("id", id);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 2;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");

                    id = data.getString("id");
                    name = data.getString("name");
                    desc = data.getString("title");
                    collectstatus  = data.getString("collection_status");
                    sharelogo = data.getString("logo");


                    msg.arg1 = 4;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }
    private void collect() {
        String token = getUserInfo("token");
        String url = myapp.getWebConfig() + "/api/banner/takeCollection";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("id", id);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 2;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");
                    String status = data.getString("status");

                    msg.obj = status;
                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    public Handler handler = new Handler() {

        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }

                    break;
                case 1:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    break;
                case 2:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    String obj = (String) msg.obj;
                    ToastUtils.show(obj);



                    break;
                case 3:
                    String collectstr = (String) msg.obj;
                    if ("1".equals(collectstr)){
                        ToastUtils.show("收藏成功");
                        tv_collect.setText("取消收藏");
                    }else if ("2".equals(collectstr)){
                        ToastUtils.show("取消收藏成功");
                        tv_collect.setText("收藏");
                    }

                    break;
                case 4:
                    if ("0".equals(collectstatus)){
                        tv_collect.setText("收藏");
                    }else if ("1".equals(collectstatus)){
                        tv_collect.setText("取消收藏");
                    }
                    tv_name.setText(name);
                    tv_desc.setText(desc);

                    break;
                case 5:
                    String user_id = getUserInfo("user_id");
                    String appid = myapp.getAppId();
//                String url = "https://www.seeland-wood.com/index/material/detail?id=13614";
                    String url = myapp.getWebConfig()+"/index/index/share?id="+id;
                    String title = name;
                    String description = desc;
                    Log.e("分享链接", url );
                    Log.e("分享链接title", title + "   链接");
                    Log.e("分享链接description", description + "   链接");
//                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
                    ShareUtil.shareToweixin(VideoDetailActivity.this, url, title, description, bitmap, appid);
                    break;
                case 11:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }

                    break;
                case 12:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    break;
            }
            switch (msg.what) {
                case 0:
                    //1.得到当前的视频播放进程
                    currentPosition = videoview.getCurrentPosition();
                    seek_progress.setProgress(currentPosition);
                    //3.更新文本播放进度
                    SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");//这里想要只保留分秒可以写成"mm:ss"
                    formatter.setTimeZone(TimeZone.getTimeZone("00:00"));
                    String hms = formatter.format(currentPosition);
                    tv_time_progress.setText(hms);

                    //4.每秒更新一次
                    handler.removeMessages(0);
                    handler.sendEmptyMessageDelayed(0, 1000);
                    break;
                case 1:
                    break;


            }
        }
    };


    public  void netPicToBmp(String src) {


        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.d("FileUtil", src);
                    URL url = new URL(src);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream input = connection.getInputStream();
                    Bitmap myBitmap = BitmapFactory.decodeStream(input);

                    //设置固定大小
                    //需要的大小
                    float newWidth = 50f;
                    float newHeigth = 50f;

                    //图片大小
                    int width = myBitmap.getWidth();
                    int height = myBitmap.getHeight();

                    //缩放比例
                    float scaleWidth = newWidth / width;
                    float scaleHeigth = newHeigth / height;
                    Matrix matrix = new Matrix();
                    matrix.postScale(scaleWidth, scaleHeigth);

                    bitmap = Bitmap.createBitmap(myBitmap, 0, 0, width, height, matrix, true);
                    Message msg = new Message();
                    msg.arg1 = 5;
                    handler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }



    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
    @Subscribe
    public void onEventMainThread(InfoEventMessage event) {
        String message = event.getMessage();
        String sr = "";
        if ("视频进度".equals(message)) {
            String type = event.getType();
            String[] split = type.split("=");
            String s = split[0];
            String time = split[1];
            tv_time_progress.setText(time);
            currentPosition = Integer.parseInt(s);
//            videoview.start();
            seek_progress.setProgress(currentPosition);
            videoview.seekTo(currentPosition);
            img_stop.setImageResource(R.mipmap.icon_play);
        }else if ("设备ID已更新退出登录".equals(message)){
            String type = event.getType();
            ExitAppUtil.getInstance().popbyexit(type,context,VideoDetailActivity.this,tv_collect);
//            popbyexit(type);
        }


    }


}
